const express = require('express');
const { query } = require('../utils/pool');
const router = express.Router();

// 药品列表
router.get('/list', async (req, res) => {
  const obj = req.query;
  if (!obj.pno) obj.pno = 1;
  if (!obj.count) obj.count = 10;
  const size = parseInt(obj.count);
  const start = (obj.pno - 1) * size;
  const result = await query(
    'select * from ih_medicine order by id desc limit ?,?; select count(*) as n from ih_medicine',
    [start, size]
  );
  console.log(result);
  res.send({
    code: 200,
    msg: '药品列表',
    data: result[0],
    total: result[1][0].n,
    pages: Math.ceil(result[1][0].n / size),
    pno: obj.pno
  });
});
// 添加药品
router.post('/add', async (req, res) => {
  const obj = req.body;
  const result = await query('insert into ih_medicine set ?', [obj]);
  console.log(result);
  res.send({ code: 200, msg: '药品添加成功' });
});
// 药品详情
router.get('/detail', async (req, res) => {
  const obj = req.query;
  const result = await query('select * from ih_medicine where id=?', [obj.id]);
  res.send({
    code: 200,
    msg: '药品详情',
    data: result
  })
});
// 修改药品
router.put('/update',async (req, res) => {
  const obj = req.body
  const result = await query('update ih_medicine set ? where id = ?',[obj,obj.id])
  if(result.changedRows === 0) {
    res.send({code: 400, msg: '修改失败'})
  } else {
    res.send({code: 200, msg: '修改成功'})
  }
})
router.delete('/',async (req, res) => {
  const obj = req.query
  console.log(obj)
  const result = await query('DELETE FROM `ih_medicine` WHERE id=?',[obj.id])
  console.log(result)
  if(result.affectedRows === 0) {
    res.send({code: 400, msg: '删除失败'})
  }else {
    res.send({code: 200, msg: '删除成功'})
  }
})

module.exports = router;
